package com.cy.detectsys.controller.detect;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cy.detectsys.entity.DetectTarget;
import com.cy.detectsys.entity.DetectTargetIp;
import com.cy.detectsys.entity.ProxynodeResource;
import com.cy.detectsys.mapper.DetectTargetMapper;
import com.cy.detectsys.model.PageDto;
import com.cy.detectsys.model.PageReqModel;
import com.cy.detectsys.service.DetectTargetIpService;
import com.cy.detectsys.service.DetectTargetService;
import com.cy.detectsys.util.R;
import com.github.pagehelper.PageHelper;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Struct;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("detectTarget")
public class DetectTargetController {


    @Resource
    private DetectTargetService baseService;

    @Resource
    private DetectTargetIpService targetIpService;

    @RequestMapping("add")
    public R add(@RequestBody DetectTarget detectTarget) {
        baseService.save(detectTarget);
        return R.ok(detectTarget);
    }
    @RequestMapping("update")
    public R update(@RequestBody DetectTarget detectTarget) {
        baseService.updateById(detectTarget);
        //更新目标的域名和IP关联信息
        targetIpService.updateByDetectTarget(detectTarget);
        return R.ok(detectTarget);
    }

    @RequestMapping("delete")
    public R delete(@RequestBody DetectTarget detectTarget) {
        baseService.removeById(detectTarget);
        return R.ok(detectTarget);
    }

    @RequestMapping("list")
    public R list(@RequestBody PageReqModel<DetectTarget> form) {
        PageHelper.startPage(form.getPage(), form.getPageSize());

        DetectTarget model = form.getModel();
        QueryWrapper<DetectTarget> detectTargetQueryWrapper = new QueryWrapper<>();
        if (StrUtil.isNotEmpty(model.getKyNetTargetEnglishName())) {
            detectTargetQueryWrapper.like("ky_net_target_english_name", model.getKyNetTargetEnglishName());
        }
        List<DetectTarget> list = baseService.list(detectTargetQueryWrapper);
        for (DetectTarget detectTarget : list) {

            String targetNameEn = detectTarget.getKyNetTargetEnglishName();
            HashMap<String, List<String>> targetIP = targetIpService.selectByTargetName(targetNameEn);

            List<String> domains = targetIP.get("domains");

            List<String> ips = targetIP.get("ips");

            detectTarget.setDomains(domains);
            detectTarget.setIps(ips);

        }
        return R.ok(PageDto.listToPageDto(list));
    }
}
